package com.piece.module.file.util.pdf.event;

import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.Style;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.VerticalAlignment;
import com.piece.module.file.util.pdf.BuilderContext;
import com.piece.module.file.util.pdf.PdfColor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FooterIEvent implements IEventHandler {

    private BuilderContext builderContext;
    private Document document;
    private int offset;

    public FooterIEvent(BuilderContext builderContext, Document document, int offset) {
        this.builderContext = builderContext;
        this.document = document;
        this.offset = offset;
    }

    @Override
    public void handleEvent(Event event) {
        if (builderContext.isShowFooter()) {
            PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
            PdfDocument pdfDoc = docEvent.getDocument();
            PageSize pageSize = pdfDoc.getDefaultPageSize();
            int pageNumber = pdfDoc.getNumberOfPages();
            Style style = new Style();
            style.setFontColor(PdfColor.getBlackColor());
            style.setFontSize(12);
            document.showTextAligned(
                    new Paragraph(String.format("- %d -", pageNumber + offset)).addStyle(style),
                    pageSize.getWidth() / 2 - 50,
                    42,
                    pageNumber,
                    TextAlignment.CENTER,
                    VerticalAlignment.MIDDLE,
                    0);
        }
    }
}
